package com.pdstudio.carrecom.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;
import com.pdstudio.carrecom.api.HttpExecuteJson;
import com.pdstudio.carrecom.api.ServiceHelper;
import com.pdstudio.carrecom.api.HttpExecuteJson.httpReturnJson;
import com.pdstudio.carrecom.app.AppContext;
import com.pdstudio.carrecom.app.UIHelper;
import com.pdstudio.carrecom.bean.LoginInfo;
import com.pdstudio.carrecom.common.BaseActivity;
import com.pdstudio.carrecom.tools.StringUtils;
import com.pdstudio.carrecom.ui.activity.account.ActivityGetPassword;
import com.pdstudio.carrecom.ui.activity.account.ActivityGoRegister;
import com.pdstudio.carrecom.R;

public class ActivityLogin extends BaseActivity implements OnClickListener {
	String mUserName, mPassword;
	boolean mAutoLogin;

	EditText metAccount, metPassword;
	CheckBox mcbAutoLogin;
	Button mbtLogin;
	Boolean autoLogin;

	SharedPreferences preferences;
	
	TextView tv_getpass,tv_register;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		setContentView(R.layout.activity_login);

		preferences = getSharedPreferences("login", MODE_PRIVATE);

		initView();
		initData();

		super.onCreate(savedInstanceState);

	}

	private void initTitleBar() {

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (metAccount != null)
			initData();
		super.onResume();
	}

	private void initView() {

		mbtLogin = (Button) findViewById(R.id.login);
		metAccount = (EditText) findViewById(R.id.account);
		metPassword = (EditText) findViewById(R.id.password);

		findViewById(R.id.login).setOnClickListener(this);
		mbtLogin.setOnClickListener(this);
		
		tv_getpass=(TextView)findViewById(R.id.unrecogpassword);
		tv_getpass.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(ActivityLogin.this,ActivityGetPassword.class);
				startActivity(intent);
			}});
		tv_register=(TextView)findViewById(R.id.gotoregister);
		tv_register.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(ActivityLogin.this,ActivityGoRegister.class);
				startActivity(intent);
			}});

	}

	private void initData() {

		// 密码(未加密)
		mUserName = AppContext.getInstance()._userName;
		mPassword = AppContext.getInstance()._userPsd;
		boolean isLogin = AppContext.getInstance()._autoLogin;

		metAccount.setText(StringUtils.isEmpty(mUserName) ? "" : mUserName);
		metPassword.setText(StringUtils.isEmpty(mPassword) ? "" : mPassword);

//		mcbAutoLogin.setChecked(isLogin);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.login:
			login();
			break;

		// case R.id.regsiter:
		// // UIHelper.StartUserRegisterActivity(ActivityLogin.this);
		// break;
		}

	}

	private void login() {
		mUserName = metAccount.getText().toString();
		mPassword = metPassword.getText().toString();
//		autoLogin = mcbAutoLogin.isChecked();

		if (!checkValue())
			return;
		
		try {
			HttpExecuteJson http = new HttpExecuteJson(this, mLoginListener);
			RequestParams rps=new RequestParams();
			rps.addBodyParameter("name", mUserName);
			rps.addBodyParameter("passwd", StringUtils.md5(mPassword));
			mbtLogin.setText("正在登录...");
			http.post(ServiceHelper.Login, rps);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
	}

	private boolean checkValue() {
		String msg = "";

		if (StringUtils.isEmpty(mUserName)) {
			msg = getString(R.string.login_check_account);
			// metAccount.setError("");
			metAccount.requestFocus();
			UIHelper.ToastMessage(getApplicationContext(), msg);
			return false;
		}

		if (StringUtils.isEmpty(mPassword)) {
			msg = getString(R.string.login_check_password);

			// metPassword.setError("");
			metPassword.requestFocus();
			UIHelper.ToastMessage(getApplicationContext(), msg);
			return false;
		}

		return true;
	}

	private void DoJson(String json){
		LoginInfo edv = null;
		try {
			edv = new Gson().fromJson(json,
					new TypeToken<LoginInfo>() {
					}.getType());
			if ((edv != null)
					&& (edv.msg.equals(ServiceHelper.msg_code_sucess))) {
				//原本在initview的代码放在这下面
				try{
					AppContext.getInstance()._isLogin = true;

					AppContext.getInstance().saveLoginInfo(mUserName + "", mPassword + "",
							false);
					
					AppContext.getInstance()._userId=Integer.parseInt(edv.id);

					Intent intent = new Intent(ActivityLogin.this, ActivityMain.class);
					startActivity(intent);
					finish();

				}catch(Exception e){
					e.printStackTrace();
				}
			}else{
				UIHelper.ToastMessage(ActivityLogin.this, "登录失败");
				mbtLogin.setText("登录");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	private httpReturnJson mLoginListener = new httpReturnJson() {
		@Override
		public void onFailure(int error, String msg) {
			UIHelper.ToastMessage(ActivityLogin.this, "登录失败" + msg);
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			UIHelper.ToastMessage(ActivityLogin.this, "登录失败");
		}

		// 获取到饲料配方类型成功
		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			// UIHelper.ToastMessage(_context,"总条数=" + result + "");
			DoJson(result);
		}
	};

	
}
